/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ro.futurefeed.view;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import org.primefaces.context.RequestContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import ro.futurefeed.api.FeedTO;
import ro.futurefeed.model.FacebookQLUser;
import ro.futurefeed.model.Feed;
import ro.futurefeed.repository.FeedRepository;
import ro.futurefeed.service.FacebookService;
import ro.futurefeed.service.UserService;
import ro.futurefeed.util.FeedAssembler;

/**
 *
 * @author georgian
 */
@Component("feedsOverview")
@Scope("request")
public class FeedsOverview{
    
    private static final Logger LOG = Logger.getLogger("FutureFeedService");
    
    @Autowired
    private UserViewData userViewData;
    
    @Autowired
    private UserService userService;
    @Autowired
    private FacebookService facebookService;
    @Autowired
    private FeedRepository feedRepository;
    
    private String code;
    private String redirectURL;
    
    public UserViewData getUserViewData() {
        return userViewData;
    }

    public void setUserViewData(UserViewData userViewData) {
        this.userViewData = userViewData;
    }
    
    public UserService getUserService() {
        return userService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public FeedRepository getFeedRepository() {
        return feedRepository;
    }

    public void setFeedRepository(FeedRepository feedRepository) {
        this.feedRepository = feedRepository;
    }

    public void refreshUserAndFeeds() {
        String facesRequestHeader = FacesContext.getCurrentInstance().getExternalContext().getRequestHeaderMap().get("Faces-Request");
        if(facesRequestHeader != null && facesRequestHeader.equals("partial/ajax")){
            //ajax call, dont refresh the user and feed list
            return;
        }
        code = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("code");
        try{
            System.out.println("Get FB user for code " + code);
            String accessToken = facebookService.getFacebookAccessToken(code);
            System.out.println("Access token is " + accessToken);
            userViewData.setAccessToken(accessToken);
            userViewData.setUser(userService.getUserWithExtendedToken(accessToken));
        }catch(Exception e){
            LOG.log(Level.SEVERE, "Error on load user: {0}", e);
            userViewData.setUser(null);
            FacesContext.getCurrentInstance().addMessage(null, 
                    new FacesMessage(FacesMessage.SEVERITY_FATAL, "ERROR", "Facebook authentification failed. Please retry later."));
        }
        if(userViewData.getUser() != null){
            List<FeedView> feeds = getFeedsForCurrentUser();
            if(feeds.isEmpty()){
                FacesContext.getCurrentInstance().addMessage(null, 
                    new FacesMessage(FacesMessage.SEVERITY_INFO, null, 
                    "Currently you dont have any future feed.\nPress 'New feed' button to add your first feed!"));
            }
        }
    }

    private List<FeedView> getFeedsForCurrentUser() {
        List<FeedView> feeds = new ArrayList<FeedView>();
        List<Feed> userFeeds = feedRepository.getUserFeeds(userViewData.getUser());
        for(Feed feed : userFeeds) {
            final FeedView feedView = FeedAssembler.toView(feed);
            feeds.add(feedView);
        }
        userViewData.setFeeds(feeds);
        LOG.log(Level.INFO, "Feeds found {0}", feeds.size());
        return feeds;
    }
    
    public void saveFeed(ActionEvent e){
        RequestContext context = RequestContext.getCurrentInstance();
        final FeedView feed = userViewData.getFeed();
        if(!StringUtils.hasText(feed.getContent())){
            addValidationError("Feed message is mandatory!");
            return;
        }
        if(!feed.isMyWall() && (feed.getFriend()==null || !StringUtils.hasText(feed.getFriendId()) || feed.getFriendId().equals("null"))){
            addValidationError("You need to enter a friend!");
            return;
        }
        Feed entityFeed = FeedAssembler.toEntity(feed);
        entityFeed.setUserKey(userViewData.getUser().getId());
        try{
            if(entityFeed.getId() == null){
                System.out.println("Save feed " + feed);
                feedRepository.save(entityFeed);
            }else{
                System.out.println("Update feed " + feed);
                feedRepository.update(entityFeed);
            }
            //refresh feeds list
            getFeedsForCurrentUser();
        }catch(Exception ex){
            LOG.log(Level.SEVERE, "Error on save user: {0}", ex);
            FacesContext.getCurrentInstance().addMessage("editDialogFeedback", 
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, null, 
                    "Error saving feed. Please retry later!"));
            context.addCallbackParam("validationFailed", true);
        }
    }
    
    public void newFeed(ActionEvent e){
        userViewData.setFeed(new FeedView());
    }
    
        
    public void deleteFeed(ActionEvent e){
        try{
            Feed oldEntityFeed = feedRepository.findById(userViewData.getFeed().getId());
            feedRepository.delete(oldEntityFeed);
            //refresh feeds list
            getFeedsForCurrentUser();
        }catch(Exception ex){
            LOG.log(Level.SEVERE, "Error on delete feed: {0}", ex);
            FacesContext.getCurrentInstance().addMessage(null, 
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", "Could not delete feed. Please retry later."));
        }
    }
    
    public List<FacebookQLUser> completeFriend(String query) {
        try{
            return facebookService.getFriends(userViewData.getAccessToken(), query);
        }catch(Exception e){
            LOG.log(Level.SEVERE, "Error getting friends: {0}", e);
            return new ArrayList<FacebookQLUser>();
        }   
    }

    private void addValidationError(String error) {
        RequestContext context = RequestContext.getCurrentInstance();
        FacesContext.getCurrentInstance().addMessage("editDialogForm:editDialogFeedback",
                new FacesMessage(FacesMessage.SEVERITY_ERROR, null,
                error));
        context.addCallbackParam("validationFailed", true);
    }
    
    public void logout() throws IOException {
        FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
        redirectURL = String.format("https://www.facebook.com/logout.php?next=%s&access_token=%s", FacebookService.HOSTANME, userViewData.getAccessToken());
        System.out.println("Logout " + redirectURL);
        FacesContext.getCurrentInstance().getExternalContext().redirect(redirectURL);
    }
}
